//
//  QDLineGraphViewController.swift
//  QDMetroClient
//
//  Created by YueWen on 2019/3/4.
//  Copyright © 2019 YueWen. All rights reserved.
//

import UIKit
import HandyJSON


/// 线网图的线路
private struct QDLine: HandyJSON {
    /// 线路的id
    var id = ""
    /// 是否不可用
    var disable = false
    /// 线路
    var name = ""
}

private extension String {

    /// 线网图每条线的跳转位置
    var lineGraphContentOffset: CGPoint {
        get {
            switch self {
                /// 3号线
            case "1": return CGPoint(x: 454.0, y: 28.0)
                /// 2号线
            case "2": return CGPoint(x: 562.3333333333334, y: -23.0)
                /// 11号线
            case "3": return CGPoint(x: 625.0, y:  -31.333333333333332)
                /// 13号线
            case "4": return CGPoint(x: 14.0, y: 280.6666666666667)
            default: return .zero
            }
        }
    }
    
    
}


/// 搜索结果cell
final class QDLineGraphResultCell: NWTableViewCell {
    
    /// 显示的标题
    let titleLabel = UILabel()
    
    override func buildView() {
        super.buildView()
        
        titleLabel.textColor = QDColors.black
        titleLabel.font = Font.regular.font(size: 16)
        
        contentView.addSubview(titleLabel)
        
        titleLabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(40)
            make.centerY.equalToSuperview()
        }
        
        bottomLineInset.left = 40
        bottomLineHeight = 0.5
        bottomLineView.backgroundColor = 230.ritl_color
    }
}


protocol QDLineGraphViewControllerPurchaseDelegate: class {
    
    // 点击购买后的回调
    func lineGraphViewController(viewController: QDLineGraphViewController, start:(stationId: String, stationName: String), end: (stationId: String, stationName: String))
    
}


extension QDLineGraphViewControllerPurchaseDelegate {
    
    func lineGraphViewController(viewController: QDLineGraphViewController, start:(stationId: String, stationName: String), end: (stationId: String, stationName: String)){}
}



/// 线网图
final class QDLineGraphViewController: NWViewController {
    
    /// 响应类型
    enum ActionType {
        /// 从在线购票界面
        case `default`
        /// 从其他界面跳入
        case other
    }
    
    
    /// 展示线网图的webView
    private let webView = WKWebView()
    /// 搜索
    fileprivate let searchView = QDLineGraphSearchView(frame: .zero)
    /// 站点信息
    private let stationView = QDLineGraphBottomStationView(frame: CGRect(origin: .zero, size: CGSize(width: UIScreen.main.ritl_width, height: 154 + BarDistance.TabBar.safeDistance)))
    /// 搜索结果的列表视图
    private let resultTableView = UITableView()
    /// 缩放的背景图
    private let zoomBackgroundView = UIImageView()
    /// 放大缩放
    private let zoomUpButton = UIButton()
    /// 缩小缩放
    private let zoomDownButton = UIButton()
    /// 缩放视图的分割线
    private let zoomSepLineView = UIView()
    /// 路线按钮
    private let lineButton = UIButton()
    /// 用于延迟释放
    private var strongSelf: QDLineGraphViewController?
    /// 导航rightItem
    lazy private var rightButtonItem: UIBarButtonItem = {
        
        let button = UIButton()
        button.setTitle("站点", for: .normal)
        button.adjustsImageWhenHighlighted = false
        button.setTitleColor(QDColors.black, for: .normal)
        button.titleLabel?.font = Font.regular.font(size: 16)
        button.addTarget(self, action: #selector(pushToStationsViewController), for: .touchUpInside)
        /// 小于11
        if (UIDevice.current.systemVersion as NSString).floatValue < 11.0 {
            button.ritl_size = CGSize(width: 42, height: 32)
        }
        
        return UIBarButtonItem(customView: button)
    }()
    
    lazy private var leftCloseButtonItem: UIBarButtonItem = {
        
        let button = UIButton()
        button.setTitle("关闭", for: .normal)
        button.adjustsImageWhenHighlighted = false
        button.setTitleColor(QDColors.black, for: .normal)
        button.titleLabel?.font = Font.regular.font(size: 16)
        button.addTarget(self, action: #selector(closeButtonDidTap), for: .touchUpInside)
        /// 小于11
        if (UIDevice.current.systemVersion as NSString).floatValue < 11.0 {
            button.ritl_size = CGSize(width: 42, height: 32)
        }
        
        return UIBarButtonItem(customView: button)
    }()
    
    
    /// 底部线路的视图
    lazy private var linesBottomView: QDLinesView = {
       
        let linesView = QDLinesView()
        
        linesView.lineDidTapHandler = { [unowned self](bottomView, index) in
            // 清除绘制
            self.clearQuery()
            // 进行绘制
            self.drawLine(lineId: self.allLines[index].id)
            // 消失
            bottomView.dismiss()
        }
        
        return linesView
        
    }()
    
    /// 底部路径规划的视图
    lazy private var linePathView: QDLinePathView = {
        
        let pathView = QDLinePathView()
        pathView.bottomButton.addTarget(self, action: #selector(purchaseButtonDidTap), for: .touchUpInside)
        
        return pathView
    }()
    
    
    //MARK: Data
    /// 存储所有的地铁站点
    private var allStations = [QDMetroStation]()
    /// 存储查询命中的地铁站点
    private var resultStations = [QDMetroStation]()
    /// 开始站点
    private var startStation = QDMetroSimpleStation()
    /// 终点站点
    private var endStation = QDMetroSimpleStation()
    /// 地铁线路
    private var allLines = [QDLine]()
    /// 代理对象
    weak var delegate: QDLineGraphViewControllerPurchaseDelegate?
    /// web桥接
    private var bridge: WebViewJavascriptBridge!
    /// 是否自动调整webView
//    private var shouldAutoMiddleWebViewAfterViewDidLoad: Bool = true
    /// 默认为从购买进入
    private var type: ActionType = .default
    
    
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }
    
    convenience init(delegate: QDLineGraphViewControllerPurchaseDelegate? = nil,type: QDLineGraphViewController.ActionType = .default) {
        self.init()
        self.type = type
        self.delegate = delegate
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    /// 购买的按钮进行点击
    @objc func purchaseButtonDidTap(){
        
        //线路界面消失
        self.dismissLinePathView()
        
        checkLogin { [unowned self] in
            
            //如果是默认
            if self.type == .default {
                self.strongSelf = self // 确保pop后能执行delegate方法
                //pop走
                self.navigationController?.popViewController(animated: true)
                // 进行回调
                self.delegate?.lineGraphViewController(viewController: self, start: (self.startStation.id, self.startStation.name), end: (self.endStation.id, self.endStation.name))
                
                self.strongSelf = nil; return
            }
            
            
//            router(platform: .metroTicket())
            
            //买票控制器
            let ticketController = QDMetroTicketViewController()
            
            ticketController.startStation = QDMetroSimpleStation(id: self.startStation.id, name: self.startStation.name)
            ticketController.endStation = QDMetroSimpleStation(id: self.endStation.id, name: self.endStation.name)
            
            self.ritl_topNavigationPush(ticketController, animated: true)
        }
        
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        navigationItem.title = "线网图"
        
        //
        navigationItem.rightBarButtonItem = rightButtonItem
        
        // webView
        webView.navigationDelegate = self
        webView.scrollView.delegate = self
        webView.scrollView.bounces = false
        webView.scrollView.maximumZoomScale = zoomMaxScale
        webView.scrollView.minimumZoomScale = zoomMinScale
        webView.contentScaleFactor = 0
        
        // bridge
        bridge = WebViewJavascriptBridge(forWebView: webView)
        WebViewJavascriptBridge.enableLogging()
        bridge.setWebViewDelegate(self)
        
        // 缩放
        zoomBackgroundView.image = "metro_zoom_background".namedImage
        zoomBackgroundView.isUserInteractionEnabled = true
        
        zoomUpButton.backgroundColor = .white
        zoomUpButton.adjustsImageWhenHighlighted = false
        zoomUpButton.setImage("metro_zoom_up".namedImage, for: .normal)
        zoomUpButton.addTarget(self, action:#selector(zoomButtonDidTap(sender:)) , for: .touchUpInside)
        
        zoomDownButton.backgroundColor = .white
        zoomDownButton.adjustsImageWhenHighlighted = false
        zoomDownButton.setImage("metro_zoom_down".namedImage, for: .normal)
        zoomDownButton.addTarget(self, action:#selector(zoomButtonDidTap(sender:)) , for: .touchUpInside)
        
        zoomSepLineView.backgroundColor = 235.ritl_color
        
        // 地铁线路/路线规划按钮
        lineButton.adjustsImageWhenHighlighted = false
        lineButton.setImage("metroline-button-metroline".namedImage, for: .normal)
        lineButton.setImage("metroline-button-lineplanning".namedImage, for: .selected)
        lineButton.addTarget(self, action: #selector(lineButtonDidTap), for: .touchUpInside)
        
        // 搜索先隐藏，等到请求站点后触发
        searchView.isHidden = true
        searchView.textField.addTarget(self, action: #selector(textFieldEditingChanged(textField:)), for: .editingChanged)
        
        // 搜索结果列表
        let resultRowHeight = 54
        resultTableView.rowHeight = CGFloat(resultRowHeight)
        resultTableView.separatorInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
        resultTableView.delegate = self
        resultTableView.isHidden = true
        resultTableView.bounces = false
        resultTableView.separatorStyle = .none
        resultTableView.dataSource = self
        resultTableView.backgroundColor = .clear
        resultTableView.tableFooterView = UIView()
        resultTableView.register(QDLineGraphResultCell.self, forCellReuseIdentifier: "cell")
        
        // 车站信息
        stationView.ritl_originY = ritl_height
        
        view.addSubview(webView)
        view.addSubview(searchView)
        view.addSubview(lineButton)
        view.addSubview(zoomBackgroundView)
        view.addSubview(resultTableView)
        view.addSubview(stationView)
        zoomBackgroundView.addSubview(zoomUpButton)
        zoomBackgroundView.addSubview(zoomSepLineView)
        zoomBackgroundView.addSubview(zoomDownButton)
        
        webView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        searchView.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(13)
            make.right.equalToSuperview().inset(13)
            make.height.equalTo(58)
            make.top.equalToSuperview().offset(13 + BarDistance.NavigationBar.height)
        }
        
        resultTableView.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().inset(20)
            make.top.equalTo(searchView.snp.bottom).inset(9)
            make.height.equalTo(resultRowHeight * 5)
        }
        
        zoomBackgroundView.snp.makeConstraints { (make) in
            make.right.equalToSuperview().inset(13)
            make.height.equalTo(102)
            make.width.equalTo(58)
            make.centerY.equalToSuperview().offset(8.5)
        }
        
        lineButton.snp.makeConstraints { (make) in
            make.width.height.equalTo(48)
            make.right.equalToSuperview().inset(20)
            make.centerY.equalToSuperview().offset(117.5)
        }
        
        zoomUpButton.snp.makeConstraints { (make) in
            make.width.height.equalTo(20)
            make.top.equalToSuperview().offset(17.5)
            make.centerX.equalToSuperview()
        }
        
        zoomSepLineView.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.right.equalToSuperview().inset(15)
            make.top.equalToSuperview().offset(49)
            make.height.equalTo(0.5)
        }
        
        zoomDownButton.snp.makeConstraints { (make) in
            make.width.height.equalTo(20)
            make.bottom.equalToSuperview().inset(20.5)
            make.centerX.equalToSuperview()
        }
        
        //开始加载
        if let url = URL(string: lineGraphWebUrl) {
            webView.load(URLRequest(url: url))
        }
        
        //请求站点
        requestAllStations()
        //请求线路
        requestAllLines()
    }
    
    
    
    /// 请求所有的站点
    private func requestAllStations(){
        
        QDNetworkingManager.requestAllStations(complete: { (_, lines) in
            
            //获得所有的站点信息
            self.allStations = lines.metroStationsWithoutRepeat()
            //展示搜索
            self.searchView.isHidden = false
            
        }) { (msg, errorType) in
            
            self.view.showTextHUD(text: msg)
        }
    }
    
    
    /// 请求所有的线路
    private func requestAllLines(){
        
        QDNetworkingManager.request(url: stationLinesUrl, isArray: true, paramteres: [String : Any](), arraySuccess: { (msg, datas) in
            
            //获得所有的线路
            self.allLines = [QDLine].deserialize(from: datas) as? [QDLine] ?? [QDLine]()
            
            //背地里刷新线路视图即可，此处可以使用懒加载优化
            self.linesBottomView.data = self.allLines.map { ($0.id,$0.name) }
            
        }) { (msg, _) in
            
            self.view.showTextHUD(text: msg)
        }
    }
    
    
    
    /// 最大缩放量
    private let zoomMaxScale = CGFloat(1.2)
    /// 最小所放量，也是最初的缩放量
    private let zoomMinScale = CGFloat(0.2)
    
    /// 缩放按钮点击
    @objc func zoomButtonDidTap(sender: UIButton){
        
        let scale = webView.scrollView.zoomScale
        
        if sender == zoomUpButton {
            
            guard scale < zoomMaxScale else { return }//超出最大限制
            scaleForWebView(change: 0.2); return
        }
        
        guard scale > zoomMinScale else { return }//低于最小限制
        scaleForWebView(change: -0.2)
    }
    
    
    /// webView 进行缩放
    ///
    /// - Parameter change: 负数为缩小，正数为放大
    private func scaleForWebView(change: CGFloat = 0){
        var scale = webView.scrollView.zoomScale
        scale =  max(zoomMinScale, min(scale + change, zoomMaxScale))  // 缩放位于0.25 - 1.7之间
        
        // 进行缩放
        webView.scrollView.setZoomScale(scale, animated: true)
    }
    
    
    
    /// 地铁线路/线路规划按钮相应
    @objc func lineButtonDidTap(){
        
        if lineButton.isSelected {//如果是线路规划
            navigationItem.leftBarButtonItem = leftCloseButtonItem //左侧按钮变为close
            showLinePathView(); return
        }
        
        dismissStationView() //隐藏站点信息
        showBottomLinesView()
        //地铁线路点击了
        print("\(lineButton.isSelected ? "线路规划" : "地铁线路")")
    }
    
    /// 关闭按钮
    @objc func closeButtonDidTap(){
 
        // 清空数据
        startStation.setContent(id: "", name: "")
        endStation.setContent(id: "", name: "")
        clearQueryAndResetOtherButtons()
    }
    
    
    /// 如果站点信息全部填充完毕，则清除数据
    func clearStationMessageAndClearQuery(){
        if !startStation.id.isEmpty && !endStation.id.isEmpty {
            startStation.setContent(id: "", name: "")
            endStation.setContent(id: "", name: "")
            clearQuery()//线路进行清除
        }
    }
}



extension QDLineGraphViewController: QDStationsViewSelectAction {
    
    /// 弹出站点信息
    @objc func pushToStationsViewController(){
        
        //搜索模式取消
        view.endEditing(true)
        searchView.textField.text = nil
        resultTableView.isHidden = true

        clearQueryAndResetOtherButtons(shouldResetOthers: (!startStation.id.isEmpty && !endStation.id.isEmpty))//清除线路绘制模式
        linesBottomView.dismiss()
        dismissLinePathView() // 清除路径规划
        
        router(platform: .stations(type: .select, delegate: self))
    }
    
    
    /// 站点信息
    func stationsViewController(didSelect stationName: String, stationId: String, line: [String]) {
        
        //如果全部存在数据，清空所有的数据
        clearStationMessageAndClearQuery()
        showStationView(id: stationId, name: stationName)
    }
}


extension QDLineGraphViewController: WKNavigationDelegate {
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        
        guard let url = navigationAction.request.url, let scheme = url.scheme, scheme == "qdmetro" else { decisionHandler(.allow);  return }
        
        // 获得站点id,站点名称
        let (id,name) = url.absoluteString.stationInfo
        // 展示详细信息
        showStationView(id: id, name: name)
        decisionHandler(.allow)
    }
    
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        //记录一次，调整位置
//        guard shouldAutoMiddleWebViewAfterViewDidLoad == true else {
//            shouldAutoMiddleWebViewAfterViewDidLoad = false; return
//        }

        //
//        guard let first = self.allLines.first else { return }
        //修改webView的起始位置
//        self.resetWebViewContentOffset(id: first.id)
    }
    
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        
//        let i = 0
    }
}





extension QDLineGraphViewController: UIScrollViewDelegate {
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        print("\(scrollView.contentOffset)")
    }
}


/// 搜索文本的处理
extension QDLineGraphViewController {
    
    /// 文本发生变化
    @objc func textFieldEditingChanged(textField: UITextField){
     
        /// 个数需要大于0
        guard !allStations.isEmpty, let text = textField.text, !text.isEmpty else {
            self.resultTableView.isHidden = true; return
        }
        
        //进行搜索
        resultStations = allStations.searchStation(by: text.clearSpaceString)
        resultTableView.isHidden = resultStations.isEmpty
        resultTableView.reloadData()
    }
}


fileprivate extension String {
    
    /// 去除空格的字符串
    var clearSpaceString: String {
        get {
            let string = self as NSString
            return string.replacingOccurrences(of: " ", with: "")
        }
    }
}





/// 结果列表的代理以及数据源
extension QDLineGraphViewController: UITableViewDelegate,UITableViewDataSource {
    
    /// 搜索结果
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return resultStations.count
    }
    
    /// 样式表
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let (cell,station) = (tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath),resultStations[indexPath.row])
        
        if let lineCell = cell as? QDLineGraphResultCell  {
            
            lineCell.titleLabel.text = station.name
            lineCell.bottomLineView.isHidden = (resultStations.count - 1 == indexPath.row)
        }

        return cell
    }
    
    
    /// 点击事件
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let station = resultStations[indexPath.row]
        
        if station.disable {
            view.showTextHUD(text: "暂未开通"); return
        }
        
        //如果全部存在数据，清空所有的数据
        clearStationMessageAndClearQuery()
        
        //设置数据
        searchView.textField.text = station.name
        searchView.textField.resignFirstResponder()
        resultTableView.isHidden = true
        //隐藏线路
        dismissLinePathView()
        linesBottomView.dismiss()
        
        //出现站点操作信息
        showStationView(id: station.id, name: station.name)
    }
}


//MARK: 底部的线路选择
extension QDLineGraphViewController {
    
    /// 展示底部的线路视图
    func showBottomLinesView(){
        view.endEditing(true)
        linesBottomView.show()
    }
    
    /// 消失
    func dismissBottomLinesView(){
        clearQuery()
        linesBottomView.dismiss()
    }
    
    /// 重置网页位置
    fileprivate func resetWebViewContentOffset(id: String = "1"){
        DispatchQueue.main.async {
            self.webView.scrollView.contentOffset = id.lineGraphContentOffset
        }
    }
}



//MARK: 所有的绘制操作
extension QDLineGraphViewController {
    
    /// 绘制线路
    func drawLine(lineId: String){
        
        bridge.callHandler("drawMetroLine", data: ["id":lineId]) { [unowned self](data) in
            
            guard let info = data as? [String: Any], let success = info["success"] as? Bool, success else { return }
            
            //表示绘制完成
            self.navigationItem.leftBarButtonItem = self.leftCloseButtonItem
            //进行缩放
            self.webView.scrollView.setZoomScale(self.zoomMinScale, animated: true)
            //进行位置摆正
            self.resetWebViewContentOffset(id: lineId)
        }
    }
    
    
    /// 清除线路
    func clearQuery(){
        bridge.callHandler("clearQuery", data: "") { (_) in }
    }
    
    
    /// 清除线路并还原各大按钮状态
    func clearQueryAndResetOtherButtons(shouldResetOthers: Bool = true){
        
        lineButton.isSelected = false
        lineButton.setImage("metroline-button-metroline".namedImage, for: .normal)
        
        // 返回按钮设置
        navigationItem.leftBarButtonItem = nil
        //关闭图层
        if shouldResetOthers { clearQuery() }
    }
}



//MARK: 从详情界面选择起始站点
extension QDLineGraphViewController: QDStationDetailViewControllerMapAction {
    
    /// 展示站点视图
    func showStationView(id: String, name: String){
        
        view.endEditing(true)
        
        // 设置站点名称
        stationView.nameLabel.text = name

        // 进行闭包设置，并捕捉变量
        stationView.actionHandler = {[unowned self] (_,type) in
            
            switch type {
                /// 消失
            case .close: self.dismissStationView(); return
                /// 存储出发站点
            case .start: self.setStations(name: name, id: id)
                /// 储存出站站点
            case .end: self.setStations(name: name, id: id, type: .end)
                /// 进入站点详情
            case .detail: self.router(platform: .stationDetail(id: id, name: name, fromMap: true, delegate: self))
            }
            
            self.dismissStationView()
        }
        
        
        UIView.animate(withDuration: 0.2) {
            self.stationView.ritl_originY = self.ritl_height - self.stationView.ritl_height + 5// 5 是图片的镂空边距
        }
    }
    
    
    /// 站点视图消失
    func dismissStationView(){
        
        UIView.animate(withDuration: 0.2) {
            self.stationView.ritl_originY = self.ritl_height
        }
    }
    
    
    /// 从站点返回的方法
    func stationDetailViewMapAction(viewController: QDStationDetailViewController,
                                    name: String,
                                    id: String,
                                    type: QDStationDetailInfoHeaderView.ClickType) {
        
        //如果全部存在数据，清空所有的数据
        clearStationMessageAndClearQuery()
        setStations(name: name, id: id, type: type)
        viewController.navigationController?.popViewController(animated: true)
    }
    
}



//MARK: 设置站点信息
extension QDLineGraphViewController {
    
    /// 根据类型设置站点
    func setStations(name: String, id: String, type: QDStationDetailInfoHeaderView.ClickType = .start){
        
        // 恢复搜索框
        searchView.textField.text = ""
        
        print("设置\(type == .start ? "进站":"出站"),id = \(id),name = \(name)")
        
        /// 相同判定
        if type == .start && endStation.id == id {
            self.view.showTextHUD(text: "起点不能与终点相同"); return
        }
        
        if type == .end && startStation.id == id {
            self.view.showTextHUD(text: "终点不能与起点相同"); return
        }
        
        switch type {
        case .start: startStation.setContent(id: id, name: name)
        case .end: endStation.setContent(id: id, name: name)
        }
        
        //启用js
        setStationInWebViewByBridge(type: type, id: id)
        //根据类型判断，弹出另一个
        checkStationMessage()
    }
    
    
    /// 设置起始站点
    private func setStationInWebViewByBridge(type: QDStationDetailInfoHeaderView.ClickType = .start,id: String) {
        
        let method = type == .start ? "assignBeginStation" : "assignEndStation"
        //js
        bridge.callHandler(method, data: ["id":id]) { (_) in }
    }
    
    
    /// 进出站点信息,是否重置了，点击线路规划则为false
    private func checkStationMessage(isReset: Bool = true){
        
        /// 都为空则不处理
        if startStation.id.isEmpty || endStation.id.isEmpty {
            return
        }
        
        // 改为选中状态，并切换成线路规划
        lineButton.isSelected = true
        lineButton.setImage("metroline-button-lineplanning".namedImage, for: .normal)
        
        if !isReset {
            showLinePathView(); return
        }
        
        view.showTextHUD(text: "正在进行线路规划", delayHidden: 10)

        //进行线路的网络请求
        QDNetworkingManager.request(url: lineGraphUrl, paramteres: ["startId": startStation.id,"endId": endStation.id], success: { [weak self](msg, data) in
            
            guard let strongSelf = self else { return }
            
            strongSelf.view.dismissHUD()
            
            guard let pathModel = QDLinePathModel.deserialize(from: data) else {
                return
            }
            
            strongSelf.linePathView.updateMessage(linePath: pathModel)
            strongSelf.showLinePathView()
            
            //
            guard let lineId = pathModel.stationInfos.first?.lineId else { return }
            //表示绘制完成
            strongSelf.navigationItem.leftBarButtonItem = strongSelf.leftCloseButtonItem
            //进行缩放
            strongSelf.webView.scrollView.setZoomScale(strongSelf.zoomMinScale, animated: true)
            //进行定点偏移
            strongSelf.resetWebViewContentOffset(id: lineId)
            
        }) { (msg, errorType) in
            
            self.lineButton.isSelected = false
            self.lineButton.setImage("metroline-button-metroline".namedImage, for: .normal)
            self.navigationItem.leftBarButtonItem = self.leftCloseButtonItem
            self.view.dismissHUD()
            self.view.showTextHUD(text: msg, delayHidden: 2)
        }
    }
}



//MARK: 线路规划视图
extension QDLineGraphViewController {
    
    /// 展示规划
    func showLinePathView(){
        view.endEditing(true)
        linePathView.show()
    }
    
    /// 取消规划
    func dismissLinePathView(){
        linePathView.dismiss()
    }
}



//MARK: 拓展工具

private extension String {
    
    /// 站点信息
    var stationInfo: (id: String, name: String) {
        get {
            if self.isEmpty { return ("","") }
            
            let nSelf = self as NSString
            let pathString = nSelf.substring(from: nSelf.range(of: "?").location + 1)
            let array = pathString.components(separatedBy: "&")
            
            // 获得真实的id以及name
            guard let nName = array.first, let nId = array.last else { return ("","") }
            
            //进行 NS 转型
            let nsName = nName as NSString
            let nsId = nId as NSString
            
            let id = nsId.substring(from: nsId.range(of: "=").location + 1).removingPercentEncoding ?? ""
            let name = nsName.substring(from: nsName.range(of: "=").location + 1).removingPercentEncoding ?? ""
            
            return (id,name)
        }
    }
}


fileprivate extension Array where Element == QDMetroStation {
    
    /// 搜索相关站点
    func searchStation(by key: String = "") -> [QDMetroStation] {
        return filter{ $0.name.contains(key) || $0.pinyin.contains(key)  }
    }
}

